<template>
    <div class="content">
        <div class="title">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }"><b>系统</b></el-breadcrumb-item>
            <el-breadcrumb-item>账号管理</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="main-content">
        <el-col>
          <el-button type="primary" @click="createDept">新建部门</el-button>
        </el-col>
        <el-col style="margin-top: 20px">
            <el-tree
              :data="deptList"
              :props="defaultProps"
              :load="loadChilden"
              lazy
              node-key="id"
              :expand-on-click-node="false"
              :render-content="renderContent">
            </el-tree>
        </el-col>
         </div>
        <el-col>
            <el-dialog :title="titleName" :visible.sync="dialogFormVisible">
                <el-form :model="form" style="margin-left: 80px">
                    <el-form-item label="部门名称">
                        <el-input v-model="form.name" auto-complete="off" style="width: 243px"></el-input>
                    </el-form-item>
                    <el-form-item label="部门id" v-if="false">
                        <el-input v-model="form.id" auto-complete="off" style="width: 243px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属省份">
                      <el-autocomplete class="info-input" 
                        @select="handleSelect" 
                        :fetch-suggestions="querySearchDealer" 
                        v-model="form.province" 
                        icon="search"
                        style="width:242px"></el-autocomplete>
                    </el-form-item>
                    <el-form-item label="上级部门">
                      <el-cascader 
                        size="large"
                        :options="deptOptions"
                        @active-item-change="handleDeptChange"
                        v-model="form.selectedDept">  
                      </el-cascader>
                    </el-form-item>
                    <el-form-item label="部门详情">
                      <el-input
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="form.description"
                        style="width: 243px">
                      </el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancle">取 消</el-button>
                    <el-button type="primary" @click="confirm">确 定</el-button>
                </div>
            </el-dialog>
        </el-col>
    </div>
</template>

<script type="text/javascript">
    import ElCol from 'element-ui/packages/col/src/col'
    import ElForm from '../../../node_modules/element-ui/packages/form/src/form.vue'
    import axios from 'axios'
    import $ from 'jquery'

    let id = 1000;

    export default{
        components: {
          ElForm,
          ElCol
        },

        data(){
            return{
              deptBizAreaId:'',
              selectedProvinceName:'',
              selectedProvinceId:'',
              timeout:null,
              deptOptions:[],
              temp:[],
              currentDeptList:[],
              titleName:'',
              parentDeptId:'',
              companyNo:sessionStorage.getItem('companyNo'),
              company:'',
              dialogFormVisible:false,
              responseContent:[],
              companies:[],
              deptForm:{
                name:'',
                deptDetail:''
              },
              form: {
                province:'',
                name: '',
                deptDetail:'',
                selectedDept:[],
                id:''
              },
              description:'',
              deptList: [],
              defaultProps: {
                children: 'children',
                label: 'label'
              }
            }
        },

        mounted(){
          this.getDeptOptions('')
        },

        beforeMount(){

        },

        methods:{
          //将查询到的子部门列表放到相应部门下
          test(deptId , options){
            let that = this
            $.each(options,function(index,value){
              if(value.value!=deptId&value.children!=''){
                that.test(deptId,value.children)
              }
              if(value.value==deptId){
                that.$http.get("/dept/list",{
                  params:{
                    parentDeptId:deptId,
                    companyNo:that.companyNo
                  }
                })
                .then((response)=>{
                  value.children=[]
                  $.each(response.data.data,function(index1,value1){
                    value.children.push({value:value1.deptId,label:value1.deptName,children:[]})
                  })
                })
              }
            })
          },
          //查询一级部门（下拉框）
          getDeptOptions(id){
            //console.log("id:"+id)
            this.$http.get("/dept/list",{
              params:{
                parentDeptId:id,
                companyNo:this.companyNo
              }
            })
            .then((response)=>{
              let that = this
              $.each(response.data.data , function(index , value){
                if(id===''){
                  that.deptOptions.push({value:value.deptId,label:value.deptName,children:[]})
                }
              })
            })
          },

          //获取部门列表（树形控件）
          getDeptList(node , resolve){
            this.$http.get("/dept/list",{
                params:{
                  parentDeptId:node.data.id,
                  companyNo:this.companyNo
                }
              })
              .then((response)=>{
                let that = this
                var data =[]
                $.each(response.data.data , function(index , value){
                  that.currentDeptList.push({id:value.deptId,parentDeptId:value.parentDeptId,name:value.deptName})
                  data.push({id:value.deptId,label:value.deptName,parentDeptId:value.parentDeptId,description:value.description,name:value.areaName,deptBizAreaId:value.deptBizAreaId})  
                })
                resolve(data)
              })
              .catch(function(error){
                console.log(error)
              })
          },
          //点击下拉时，获取子列表
          loadChilden(node , resolve){
            setTimeout(()=>{
              this.getDeptList(node , resolve)
            },500)
          },
          //将子部门插入相应部门下
          handleDeptChange(Dept){
            //this.getDeptOptions(Dept)
            var i 
            i = Dept.length
            this.form.selectedDept = Dept
            setTimeout(_=>{
              // this.getDeptOptions(Dept[i-1])
              this.test(Dept[i-1],this.deptOptions)
            },300)
          },

          cancle(){
            this.dialogFormVisible=false
          },
          //新建部门
          confirm(){
            var i 
            var content={}
            content.areaId = this.selectedProvinceId
            content.areaName = this.selectedProvinceName
            content.deptBizAreaId = this.deptBizAreaId
            if(this.form.id==''){   //新建部门
              i = this.form.selectedDept.length
              content.parentDeptId=this.form.selectedDept[i-1]
              content.companyNo = this.companyNo
              content.deptName = this.form.name
              content.description = this.form.description
              this.$http.post("/dept/saveDept",content)
              .then((response)=>{
                if(response.data.success){
                  this.dialogFormVisible=false
                  this.$message(response.data.message)
                }else{
                  this.$message(response.data.message)
                }
              })
              .catch(function(error){
                console.log(error)
              })
            }else{               //修改部门
              var i=0
              i = this.form.selectedDept.length
              if(i!=0)
              {
                content.parentDeptId=this.form.selectedDept[i-2]
              }else{
                content.parentDeptId=''
              }
              
              content.deptId = this.form.id
              content.companyNo = this.companyNo
              content.deptName = this.form.name
              content.description = this.form.description
              this.$http.put("/dept/editDept",content)
              .then((response)=>{
                // console.log(response)
                if(response.data.success){
                  this.dialogFormVisible=false
                  this.$message(response.data.message)
                }else{
                  this.$message(response.data.message)
                }
              })
              .catch(function(error){
                console.log(error)
              })
            }
          },

          createDept(){
            this.dialogFormVisible=true
            this.form={name: '',
                deptDetail:'',
                selectedDept:[],
                id:'',
                province:''}
            this.titleName = '新建部门'
          },
          //点击修改时加载该部门所有上级部门
          getAllParentDeptId(parentId){
            let that = this
            this.temp = []
            //console.log(this.currentDeptList)
            if(parentId!=null){
              $.each(this.currentDeptList,function(index,value){
                if(value.id==parentId){
                  // that.form.selectedDept.push(value.id)
                  that.getAllParentDeptId(value.parentDeptId)
                  that.form.selectedDept.push(value.id)
                  that.temp.push({id:value.id,name:value.name})
                }
              })
            }
          },

          handleSelect(item){
            this.selectedProvinceId = item.id
            this.selectedProvinceName = item.value
          },

          querySearchDealer(queryString,cb){
            let that = this
            var result = []
            this.$http.get('/dept/getProvinceList',{
              params:{
                keyword:this.form.province
              } 
            })
            .then((response)=>{
              $.each(response.data.data,function(index,value){
                result.push({value:value.provinceName,id:value.provinceId})
              })
              clearTimeout(that.timeout)
              that.timeout=setTimeout(()=>{
                cb(result);
              },3000*Math.random())
            })
            .catch((error)=>{
              console.log(error)
            })
          },

          //初始化deptOptions
          initDeptOptions(deptOptions,node){
            let that = this
            let deptList = []
            $.each(deptOptions,function(index,dept){
              if(node.id!=dept.value){
                that.initDeptOptions(dept.children,node)
              }
              dept.children.push({label:node.name,value:node.id,children:[]})
            })
          },
          //点击修改，弹出dialog
          ChangeDeptInfo(store,data){
            let that = this
            this.deptBizAreaId = data.deptBizAreaId
            this.titleName = '修改部门信息'
            this.dialogFormVisible = true
            this.form.name=data.label
            this.form.description=data.description
            this.form.province = data.name
            this.form.id = data.id
            this.form.selectedDept=[]
            this.getAllParentDeptId(data.id)
            $.each(this.temp,function(index,value){
              that.initDeptOptions(that.deptOptions,value)
            })
            
          },

          remove(store, data) {
            //console.log("data:"+JSON.stringify(data))
            this.$http.get("/dept/delete/"+data.id)
            .then((response)=>{
              // console.log("response:"+JSON.stringify(response))
              // console.log("success:"+response.data.success)
              if(response.data.success){
                store.remove(data);
              }
            })
            .catch(function(error){
              console.log(error)
            })
          },

          renderContent(h, { node, data, store }) {
              return(
                  <span>
                      <span>
                        <span>{node.label}</span>
                      </span>
                      <span style="float: right; margin-right: 20px">
                        <el-button size="mini" on-click={ () => this.remove(store, data) }>删除</el-button>
                        <el-button size="mini" on-click={ () => this.ChangeDeptInfo(store, data) }>修改部门信息</el-button>
                      </span>
                  </span>);
          }
        },
    }
</script>

<style lang="scss" scoped>
.content {
  padding: 10px;
  background: #F7F7F7;
  .title {
    color: #99A9BF;
    font-size: 14px;
    line-height: 18px;
    margin: 8px 0px 10px 0px;
  }
  .main-content {
    background: #fff;
    position: fixed;
    top: 96px;
    bottom: 10px;
    left: 216px;
    right: 16px;
    overflow: auto;
    padding: 20px;
  }
}
</style>